package Stackdemo;

import java.util.Arrays;


public class MyStack {
    public int[] elem;
    public int usedSize;
    //记录当前元素个数,还是放元素时数组的下标
    public MyStack() {
        this.elem = new int[10];
    }

    public void push(int val){
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[this.usedSize] = val;
        this.usedSize++;
    }
    //判断是否为满
    public boolean isFull(){
        return this.usedSize == this.elem.length;
    }
    //出栈
    public int pop() {
        if(empty()){
            throw new RuntimeException("栈为空");
        }
        int val = this.elem[this.usedSize-1];
        this.usedSize--;
        return val;
    }
    //获取栈顶元素
    public int peek() {
        if(empty()){
            throw new RuntimeException("栈为空");
        }
        return this.elem[this.usedSize-1];
    }
    //判断是否为空
    public boolean empty() {
        return this.usedSize == 0;
    }
    //栈元素个数
    public int size(){
        return this.usedSize;
    }



    public static void main(String[] args) {
        MyStack s = new MyStack();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        System.out.println(s.size()); // 获取栈中有效元素个数---> 4
        System.out.println(s.peek()); // 获取栈顶元素---> 4
        s.pop(); // 4出栈，栈中剩余1 2 3，栈顶元素为3
        System.out.println(s.pop()); // 3出栈，栈中剩余1 2 栈顶元素为2
        s.pop();
        s.pop();
        if(s.empty()){
            System.out.println("栈空");
        }else{
            System.out.println(s.size());
        }
    }
}
